import 'dart:async';

import 'package:alipay_kit/alipay_kit_platform_interface.dart';
import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:alipay_kit/alipay_kit.dart';

import '../../network/Api.dart';
import '../../utils/loading.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class Pay4ChangeUi extends StatelessWidget {
  const Pay4ChangeUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _Pqy4ChangeWidget();
  }
}

class _Pqy4ChangeWidget extends StatefulWidget {
  const _Pqy4ChangeWidget({Key? key}) : super(key: key);

  @override
  State<_Pqy4ChangeWidget> createState() => _Pqy4ChangeWidgetState();
}

class _Pqy4ChangeWidgetState extends State<_Pqy4ChangeWidget> {
  final List _list = [];
  late final StreamSubscription<AlipayResp> _paySubs;
  late final StreamSubscription<AlipayResp> _authSubs;

  bool _isSelected = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getProList();
    _paySubs = AlipayKitPlatform.instance.payResp().listen(_listenPay);
    _authSubs = AlipayKitPlatform.instance.authResp().listen(_listenAuth);
  }

  @override
  void dispose() {
    _paySubs.cancel();
    _authSubs.cancel();
    super.dispose();
  }

  void _listenPay(AlipayResp resp) {
    final String content = 'pay: ${resp.resultStatus} - ${resp.result}';
  }

  void _listenAuth(AlipayResp resp) {
    final String content = 'pay: ${resp.resultStatus} - ${resp.result}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppWidget.titleBar("增加机遇"),
      body: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                color: const Color(0xFFF4F4F4),
                height: 12,
              ),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: IconText(
                  "增加偶遇机会  ",
                  beforeText: false,
                  icon: Image.asset(
                    "images/ic_question.png",
                    width: 14,
                    height: 14,
                  ),
                  style: const TextStyle(color: Color(0xFF313131)),
                ),
              ),
              SizedBox(
                height: 82,
                child: ListView.builder(
                    itemCount: _list.length,
                    scrollDirection: Axis.horizontal,
                    itemBuilder: (ctx, index) {
                      return _buildMoneyItem(_list[index], index);
                    }),
              ),
              const SizedBox(
                height: 22,
              ),
              Container(
                color: const Color(0xFFF4F4F4),
                height: 12,
              ),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: Text(
                  "支付方式",
                  style: TextStyle(color: ThemeColor.textColor),
                ),
              ),

              // _payWay("images/ic_balance.png", "余额支付", 0),
              // _payWay(kIsWeb ?"ic_wechat_green":'images/ic_alipay.png', kIsWeb ? "微信支付" :'支付宝支付', 0),
              // _payWay('images/ic_alipay.png', '支付宝支付', 0),
              _payWay('images/ic_wechat_green.png', '微信支付', 0),
            ],
          ),
          Positioned(
            bottom: 56,
            child: GestureDetector(
              onTap: () {
                if (_checkId?.isNotEmpty == true) {
                  // if (_payWayGroupValue == 0) {
                  //   // _payoutByBalance();
                  //   _toAliPay(context);
                  // } else if (_payWayGroupValue == 1) {
                  //   _payoutByWechat(context);
                  // }

                  _bindWechat();
                }
              },
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 16),
                width: MediaQuery.of(context).size.width - 32,
                height: 44,
                decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(22)),
                    color: ThemeColor.appColor),
                alignment: Alignment.center,
                child: const Text(
                  "立即增加",
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  _bindWechat() {
    fluwx.sendWeChatAuth(
        scope: "snsapi_userinfo", state: 'wechat_sdk_demo_test');
    _wechatCallbackss();
  }

  void _wechatCallbackss() async {
    fluwx.weChatResponseEventHandler
        .distinct((a, b) => a == b)
        .listen((res) async {
      if (res is fluwx.WeChatAuthResponse) {
        print(
            'ffff ${res.code} \n${res.type} \n${res.state} \n${res.country}  \n${res.lang} \n${res.errStr} \n${res.errCode} \n${res.isSuccessful}');
        String? code = res.code;
        if (res.isSuccessful) {
          var res = await HttpRequest.request(
              'activites/order/queryUniqueIdenty',
              params: {"code": code, "index": 'app'});
          if (res != null && res['code'] == 0) {
            String data = res['data'];
            _payoutByWechat(context, openId: data);
          }
        } else {
          toast(res.errStr ?? "微信授权绑定失败[${res.errCode}]");
        }
      }
    });
  }

  var _checkMoney = 1.3;
  String? _checkId = "";

  Widget _buildMoneyItem(dynamic data, int index) {
    final money = (data['goodsPrice'] ?? 0) / 100.00;
    final count = data['goodsNum'] ?? 0;

    if (_checkMoney == money) {
      _checkId = data["id"];
    }
    return GestureDetector(
        onTap: () {
          _checkId = data["id"];
          setState(() {
            _checkMoney = money;
            _isSelected = true;
          });
        },
        child: Container(
          width: 104,
          height: 82,
          margin: EdgeInsets.only(
              left: index > 0
                  ? 38
                  : (MediaQuery.of(context).size.width - 246) / 2),
          alignment: Alignment.center,
          decoration: ShapeDecoration(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)),
              color:
                  _checkMoney == money || (_isSelected == false && index == 0)
                      ? const Color.fromRGBO(239, 233, 255, 1)
                      : Color(0xFFF7F7F7)
              // color: Color(_checkMoney == money ?  0xFFFEE4EC : 0xFFF7F7F7)
              ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconText(
                " $count次",
                icon: Image.asset(
                  "images/ic_invite_ax.png",
                  width: 16,
                  height: 16,
                ),
                style: TextStyle(color: ThemeColor.textColor, fontSize: 20),
              ),
              const SizedBox(
                height: 10,
              ),
              Text(
                "￥$money元",
                style: const TextStyle(fontSize: 14, color: Color(0xFF848484)),
              ),
            ],
          ),
        ));
  }

  int _payWayGroupValue = 0;

  Widget _payWay(String icon, String text, int index) {
    return Container(
      height: 36,
      margin: const EdgeInsets.only(bottom: 22),
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          IconText(
            "    $text",
            icon: Image.asset(
              icon,
              width: 36,
              height: 36,
            ),
            style: const TextStyle(color: Color(0xFF313131), fontSize: 14),
          ),
          Radio(
              activeColor: ThemeColor.appColor,
              value: index,
              groupValue: _payWayGroupValue,
              onChanged: (v) {
                setState(() {
                  print(_payWayGroupValue);
                  _payWayGroupValue = v as int;
                });
              })
        ],
      ),
    );
  }

  /// 获取商品列表
  _getProList() {
    loading(() async {
      final res = await Api.getInstance().proList();
      if (res['code'] == 0) {
        if (res['rows'] != null && res['rows'].length > 0) {
          setState(() {
            _list.addAll(res['rows']);
            _checkId = _list[0]['id'];
          });
        } else {
          toast("系统故障...");
        }
      } else {
        toast(res['msg']);
      }
    });
  }

  /// 余额支付
  _payoutByBalance() {
    loading(() async {
      final res = await Api.getInstance().payoutByBalance(_checkId!);
      if (res['code'] == 0) {
        Navigator.of(context).pop(int.parse("${res['data'] ?? 0}"));
      } else {
        toast(res['msg'] ?? "未知错误");
      }
    });
  }

  _wePayCallback(res) {
    if (res == 'ok') {
      _paySuccess();
    } else {
      toast('支付失败');
    }
  }

  //
// 支付宝支付
  void _toAliPay(BuildContext context) async {
    // final isInstall = await AlipayKitPlatform.instance.isInstalled();
    // print('oooo  $isInstall');
    // if (isInstall) {
    //   toast("未安装支付宝App");
    //   return;
    // }
    loading(() async {
      final res = await Api.getInstance().payoutBylipay(_checkId!);
      print(res['data']['data']['payPath']);
      final payInfo = res['data']['data']['payPath'];
      AlipayKitPlatform.instance.pay(
        orderInfo: payInfo,
        dynamicLaunch: true,
      );
      AlipayKitPlatform.instance.payResp().listen((event) {
        print('vvvv $event');
        if (event.isSuccessful) {
          _paySuccess();
        } else if (event.isCancelled) {
          toast('取消支付~');
        } else {
          toast(event.memo.toString());
        }
      });
    });

    // final res = await Api.getInstance().payoutBylipay(_checkId!);
    // print('============');
    // print(res);
    // // 检测是否安装支付宝
    // // MethodChannelAlipayKit(pay);
    // final isInstall = await AlipayKitPlatform.instance.isInstalled();
    //
    // if (isInstall) {
    //   print("未安装支付宝app");
    // //   return;
    // }
    //
    // Tobias tobias = Tobias();
    // var result = await tobias.isAliPayInstalled;
    // if(result){
    //
    //
    // if (res['code'] == 0 ) {
    //
    // tobias.pay(payInfo.toString());
    //
    //
    // AlipayKitPlatform.instance.pay(orderInfo: payInfo,dynamicLaunch:true,);
    //
    // var payResult = await tobias.pay(payInfo,);
    //
    //
    // if (payResult['result'] != null) {
    //   if (payResult['resultStatus'] == '9000') {
    //     toast("支付宝支付成功");
    // //     // Get.back(result: true);
    //   } else if (payResult['resultStatus'] == '6001') {
    //     toast("支付宝支付失败");
    //   } else {
    // //
    //     toast("未知错误");
    //   }
    // }
    // }
    //
    // } else {
    //   toast("未安装支付宝");
    // }
  }

  /// 微信支付
  _payoutByWechat(BuildContext context, {String openId = ''}) async {
    loading(() async {
      if (openId.isEmpty) {
        toast('未拿到微信openId');
      }
      final res = await Api.getInstance().payoutByWechat(_checkId!, openId);
      if (res['code'] == 0 &&
          res['data'] != null &&
          res['data']['signature'] != null) {
        final payInfo = res['data']['signature'];
        if (kIsWeb) {
          // final jsCtx = js.context;
          // jsCtx['wePayCallback'] = _wePayCallback;
          // jsCtx.callMethod(
          //     "onBridgeReady",
          //     [
          //       payInfo['appId'],
          //       payInfo['timestamp'].toString(),
          //       payInfo['nonce'],
          //       payInfo['pack'],
          //       "MD5",
          //       payInfo['signature']
          //     ]
          // );
        } else {
          fluwx.payWithWeChat(
              appId: payInfo['appId'],
              partnerId: payInfo['partnerId'],
              prepayId: payInfo['prepayId'],
              packageValue: payInfo['pack'],
              nonceStr: payInfo['nonce'],
              timeStamp: payInfo['timestamp'],
              sign: payInfo['signature']);
          fluwx.weChatResponseEventHandler.listen((event) {
            if (event.isSuccessful) {
              _paySuccess();
            } else {
              print('vvvv ${event.errStr}  ${event.errCode}');
              if (event.errCode == -2) {
                toast("用户取消支付了~");
              } else {
                toast(event.errStr.toString());
              }
            }
          });
        }
      } else {
        toast(res['msg']);
      }
    });
  }

  _paySuccess() {
    // toast("支付成功");
    int buyNum = 0;
    for (var e in _list) {
      if (e['id'] == _checkId) {
        buyNum = e['goodsNum'] ?? 0;
        break;
      }
    }
    Navigator.of(context).pop(buyNum);
  }
}
